<?php

namespace app\common\business;

use app\common\model\mysql\Admin;

use think\Exception;

class Login
{

    public function __construct()
    {
        $this->model = (new Admin());
    }

    /**
     * 验证码接口
     */
    public function getCaptcha()
    {
        //验证码唯一标识
        $uniqid = uniqid(mt_rand(100000,999999));

        //生成验证码地址
        $src = captcha_src($uniqid);
        //返回数据
        return [
          'src' => 'http://adminapi.wang.com'.$src,
          'uniqid' => $uniqid
        ];
    }

    /**
     * 登录接口
     */
    public function login($data)
    {

        if(!captcha_check($data['code'])){
            throw new Exception('验证码错误');
        }
        $userName = $data['username'];
        $userData = $this->model->getSelect(['username'=>$userName])->toArray();
        if(!$userData){
            throw new Exception('没有这个用户');
        }
        $password = $userData[0]['password'];
        if($password != encrypt_password($data['password'])){
            throw new Exception('密码错误');
        }
        $userId = $userData[0]['id'];
        //生成token
        $tokenObjPath = \ClassAttr::getTokenClass();
        $jwtObj = \ClassAttr::initClass('jwtToken',$tokenObjPath);
        $token = $jwtObj::token(['user_id'=>$userId,'username' => $userName]);

        $this->model->updateNewData(['last_login_time' => time()],['id'=>$userId]);
        //返回数据
        $result = [
            'token' => $token,
            'user_id' => $userId,
            'username' => $userName,
            'nickname' => $userData[0]['nickname'],
            'email'   => $userData[0]['email']
        ];
        return $result;

    }
}